package com.lxq;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
import java.nio.channels.WritableByteChannel;

/**
 * @author 龙小虬
 * @date 2021/4/12 12:21
 */
public class MyLoadClass extends ClassLoader{

    private String fileName;

    private File file;

    public MyLoadClass(String fileName){
        this.fileName = fileName;
    }

    public long getLastModified(){
        return file.lastModified();
    }

    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        try {
            file = new File(fileName);
            byte[] data = getClassFileBytes(file);
            return defineClass(name,data,0,data.length);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    //此方法不需要理解
    private byte[] getClassFileBytes(File file) throws Exception {
        FileInputStream fileInputStream = new FileInputStream(file);
        FileChannel fileChannel = fileInputStream.getChannel();
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        WritableByteChannel writableByteChannel = Channels.newChannel(byteArrayOutputStream);
        ByteBuffer byteBuffer = ByteBuffer.allocateDirect(1024);
        while (true){
            int i = fileChannel.read(byteBuffer);
            if(i==0 || i==-1){
                break;
            }
            byteBuffer.flip();
            writableByteChannel.write(byteBuffer);
            byteBuffer.clear();
        }
        fileInputStream.close();
        return byteArrayOutputStream.toByteArray();
    }
}
